<template>
  <view class="app-container aftercare-apply">
    <view class="flex-1 p-20" style="overflow-y: auto">
      <view class="my-card">
        <u-form ref="formRef" :model="form" :rules="rules" label-width="6em">
          <u-form-item required label="商品列表" prop="lines">
            <u-text
              align="right"
              :text="linesText ? linesText : '请选择需要退款的商品'"
              :type="linesText ? '' : 'info'"
              suffix-icon="arrow-right"
              @click="popupShow = true"
            ></u-text>
          </u-form-item>
          <u-form-item required label="类型" prop="type">
            <u-text
              align="right"
              :text="typeText ? typeText : '请选择退款类型'"
              :type="typeText ? '' : 'info'"
              suffix-icon="arrow-right"
              @click="typePickerShow = true"
            ></u-text>
          </u-form-item>
          <u-form-item required label="原因" prop="reason">
            <u-text
              align="right"
              :text="reasonText ? reasonText : '请选择退款原因'"
              :type="reasonText ? '' : 'info'"
              suffix-icon="arrow-right"
              @click="reasonPickerShow = true"
            ></u-text>
          </u-form-item>
          <u-form-item required label="备注" prop="remark">
            <up-textarea
              v-model="form.remark"
              placeholder="请输入备注"
            ></up-textarea>
          </u-form-item>
        </u-form>
      </view>
      <u-popup :show="popupShow" mode="bottom" @close="popupShow = false">
        <view class="popuo-content">
          <view class="main">
            <u-checkbox-group v-model="checked" :border="false">
              <view class="line-list">
                <u-checkbox
                  v-for="(item, index) in detail.lines"
                  :key="index"
                  :name="item.id"
                >
                  <template #label>
                    <view class="line-item">
                      <up-image
                        width="80"
                        height="80"
                        radius="10"
                        :src="item.product.image_url"
                        :lazy-load="true"
                      ></up-image>
                      <view class="line-item-right">
                        <view class="goods-name">{{ item.product.name }}</view>
                        <view class="goods-qty">x {{ item.quantity }}</view>
                        <view class="goods-price">
                          <text class="price">
                            ￥{{ item.product.sale_price }}
                          </text>
                          <text class="unit">/{{ item.product.uom.name }}</text>
                        </view>
                      </view>
                      <u-number-box
                        v-model="item.quantity"
                        :min="item.product.min_sale_number"
                        :max="item.quantity"
                        integer
                        disabledInput
                      ></u-number-box>
                    </view>
                  </template>
                </u-checkbox>
              </view>
            </u-checkbox-group>
          </view>
          <view class="popup-actions">
            <u-button @click="popupShow = false">取消</u-button>
            <view style="width: 20rpx"></view>
            <u-button type="primary" @click="handleSelectLineConfirm"
              >确认</u-button
            >
          </view>
        </view>
      </u-popup>
      <u-picker
        :show="typePickerShow"
        :columns="columns1"
        keyName="label"
        closeOnClickOverlay
        @cancel="typePickerShow = false"
        @confirm="handleTypeConfirm"
      ></u-picker>
      <u-picker
        :show="reasonPickerShow"
        :columns="columns2"
        keyName="label"
        closeOnClickOverlay
        @cancel="reasonPickerShow = false"
        @confirm="handleReasonConfirm"
      ></u-picker>
    </view>
    <view class="actions">
      <u-button type="primary" @click="handleSubmit">提交</u-button>
    </view>
  </view>
</template>

<script setup>
import { onReady, onShow } from "@dcloudio/uni-app";
import { computed, reactive, ref } from "vue";
import { orderDetail } from "@/common/apis/order.js";
import { useStore } from "vuex";

const store = useStore();

const props = defineProps({
  id: String,
});

const formRef = ref();

const detail = reactive({
  code: "",
  created_at: "",
  customer_address: "",
  customer_name: "",
  customer_phone: "",
  express_amount: "",
  id: 0,
  is_active: false,
  lines: [],
  merchant: { id: 0, name: "" },
  remark: "",
  status: "pending",
  supplier: { id: 0, name: "" },
  total_price: "",
  total_stand_price: "",
  updated_at: "",
});

const form = reactive({
  id: props.id,
  lines: [],
  type: "",
  reason: "",
  remark: "",
});

const popupShow = ref(false);

const typePickerShow = ref(false);

const reasonPickerShow = ref(false);

const checked = ref([]);

const selectLines = ref([]);

const columns1 = ref([
  [
    { label: "退货退款", value: "return" },
    { label: "仅退款", value: "refund" },
    { label: "换货", value: "replace" },
    { label: "补发商品", value: "reissue" },
  ],
]);

const columns2 = ref([
  [
    { label: "商品质量问题", value: 1 },
    { label: "商品与页面描述不符", value: 2 },
    { label: "商品破损/包装问题", value: 3 },
    { label: "少件/未收到货", value: 4 },
    { label: "发错货", value: 5 },
    { label: "价格问题", value: 6 },
    { label: "假冒品牌", value: 7 },
    { label: "其他原因", value: 8 },
  ],
]);

const rules = {
  lines: [
    {
      validator: (rule, value, callback) => {
        return Boolean(value.length);
      },
      message: "请选择需要退款的商品",
      trigger: ["change"],
    },
  ],
  type: [{ required: true, message: "请选择退款类型", targger: ["change"] }],
  reason: [
    {
      type: "number",
      required: true,
      message: "请选择退款原因",
      targger: ["change"],
    },
  ],
  remark: [{ required: true, message: "请选择退款备注", targger: ["change"] }],
};

const linesText = computed(() => {
  if (selectLines.value.length) {
    return selectLines.value.map((i) => i.product.name).join("、");
  }
  return "";
});

const typeText = computed(() => {
  const type = columns1.value[0].find((i) => i.value == form.type);
  if (type) {
    return type.label;
  }
  return "";
});

const reasonText = computed(() => {
  const c = columns2.value[0].find((i) => i.value == form.reason);
  if (c) {
    return c.label;
  }
  return "";
});

async function fetchOrderDetail() {
  const response = await orderDetail(props.id);
  if (response) {
    Object.assign(detail, response);
  }
  return response;
}

function handleSelectLineConfirm() {
  selectLines.value = [];
  form.lines = [];
  checked.value.forEach((id) => {
    const c = detail.lines.find((i) => i.id == id);
    selectLines.value.push(c);
    form.lines.push({ line_id: c.id, quantity: c.quantity });
  });
  popupShow.value = false;
}

function handleTypeConfirm(e) {
  const { value } = e;
  if (value[0]) {
    form.type = value[0].value;
  }
  typePickerShow.value = false;
}

function handleReasonConfirm(e) {
  const { value } = e;
  if (value[0]) {
    form.reason = value[0].value;
  }
  reasonPickerShow.value = false;
}

async function handleSubmit() {
  const valid = await formRef.value.validate();
  if (valid) {
    uni.showLoading();
    try {
      const response = await store.dispatch("fetchApplyAftercare", form);
      uni.hideLoading();
      if (response) {
        uni.showModal({
          content: "申请售后成功",
          cancelText: "返回",
          confirmText: "去看看",
          success: (res) => {
            if (res.cancel) {
              uni.navigateBack();
            } else {
              uni.$u.route({
                url: "/pages/order/aftercare/list",
              });
            }
          },
        });
      }
    } catch (err) {
      uni.$u.toast(err.data.error);
      uni.hideLoading();
    }
  }
}

onShow(() => {
  fetchOrderDetail();
});

onReady(() => {
  formRef.value.setRules(rules);
});
</script>

<style lang="scss" scoped>
.actions {
  display: flex;
  align-items: center;
  padding: 20rpx 20rpx calc(20rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  background-color: #fff;
  gap: 20rpx;
}

.popuo-content {
  padding: 20rpx 20rpx calc(20rpx + env(safe-area-inset-bottom));

  .main {
    box-sizing: border-box;
    overflow-y: auto;
    max-height: 500px;

    .line-list {
      padding: 0 20rpx;

      .line-item {
        padding: 20rpx 0;
        border-bottom: 2rpx solid #f0f0f0;
        display: flex;
        justify-content: space-between;

        .line-item-right {
          margin-left: 20rpx;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          flex: 1;
          padding: 10rpx 0;

          .goods-name {
            font-size: 30rpx;
            font-weight: bold;
            margin-bottom: 10rpx;
          }

          .price {
            font-size: 32rpx;
            font-weight: bold;
            color: #ff0000;
          }

          .goods-qty {
            font-size: 24rpx;
            color: #999999;
          }
        }
      }

      & .line-item:last-child {
        border-bottom: 0;
      }
    }
  }

  .popup-actions {
    display: flex;
  }
}
</style>
